package com.activity.gaswatchermtl;

import java.util.ArrayList;

import com.activity.gaswatchermtl.R;
import com.activity.gaswatchermtl.dialog.DialogFilters;
import com.activity.gaswatchermtl.fragment.FragmentTabFavorite;
import com.activity.gaswatchermtl.fragment.FragmentTabList;
import com.activity.gaswatchermtl.fragment.FragmentTabMap;
import com.app.Const;
import com.google.android.gms.maps.model.LatLng;
import com.inf8405.db.DAOStations;
import com.inf8405.db.SQLiteHelper;

import com.module.StationFinder.Station;
import com.module.StationFinder.StationList;
import com.module.StationFinder.AsyncTask.LoadNearGasStationTask;
import com.module.helper.AlertDialogHelper;
import com.module.helper.InternetHelper;

import android.location.Location;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class StartActivity extends LocationActivity implements DialogFilters.DialogFiltersListener {

	private InternetHelper internetHelper_ = null;

	private LoadNearGasStationTask stationFinder_;

	private StationList listStation_ = null;
	
	private FragmentTabList ListFragment_ = null;
	private FragmentTabMap MapFragment_ = null;
	private FragmentTabFavorite FavoriteFragment_ = null;
	
	private SharedPreferences settingsFilter_ = null;

	//Geocoder geocoder_;
	DAOStations daostations_;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start);
		
		internetHelper_ = new InternetHelper(this);

		settingsFilter_ = getSharedPreferences("FILTER", 0);
		
		//ActionBar gets initiated
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		//Tell the ActionBar we want to use Tabs.
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		//initiating both tabs and set text to it.
		ActionBar.Tab listTab = actionBar.newTab().setText(R.string.tab_list);
		ActionBar.Tab mapTab = actionBar.newTab().setText(R.string.tab_map);
		ActionBar.Tab favTab = actionBar.newTab().setText(R.string.tab_fav);

		//create the two fragments we want to use for display content
		ListFragment_ = new FragmentTabList();
		MapFragment_ = new FragmentTabMap();
		FavoriteFragment_ = new FragmentTabFavorite();
		
		//set the Tab listener. Now we can listen for clicks.
		listTab.setTabListener(new MyTabListener(ListFragment_));
		mapTab.setTabListener(new MyTabListener(MapFragment_));
		favTab.setTabListener(new MyTabListener(FavoriteFragment_));

		//add the two tabs to the actionbar
		actionBar.addTab(mapTab);
		actionBar.addTab(listTab);
		actionBar.addTab(favTab);
		actionBar.selectTab(listTab);

		//this.deleteDatabase("stationsDBTEST3.db");
		refreshStationList();
	}
	

	public void onStationListUpdated() {
		if (ListFragment_ != null && stationFinder_ != null){
			if (stationFinder_.isExecutionFinished()) {
				listStation_ = stationFinder_.getStationList();
				removeUnwantedStation(listStation_);
			}
			ListFragment_.refreshStationList(listStation_);
			MapFragment_.refreshStationList(listStation_);
		}
	}
	
	public void refreshStationList() {
		Location loc = getLocation();
		boolean internetOK = internetHelper_.isInternetDisponible();
		
		// calling background Async task to load Google Places
		if (loc != null && internetOK) {			
			stationFinder_ = new LoadNearGasStationTask(this, 
					loc.getLatitude(), 
					loc.getLongitude(), 
					settingsFilter_.getInt("DISTANCE", 1)*1000);
			stationFinder_.execute();	
		} else {
			if (!internetOK) {
				AlertDialogHelper.showAlertDialog(this,
						getString(R.string.internet_error_label),
						getString(R.string.internet_error_message),
						null);
			}
			
			if (loc == null) {
				AlertDialogHelper.showAlertDialog(this,
						getString(R.string.location_error_label),
						getString(R.string.location_error_message),
						null);
			}
		}
	}
	
    @SuppressLint("DefaultLocale")
	private StationList removeUnwantedStation(StationList stationList) {
        
        SharedPreferences settings = getSharedPreferences(Const.SETTINGS_FILTERS, 0);
        ArrayList<Station> toRemove = new ArrayList<Station>();
    	
        for (Station station : stationList.results) {
    		String tmpName = station.name.toLowerCase();
    		
    		boolean oneFound = false;
    		for (String tag : Const.SETTINGS_FILTERS_STATIONS) {
    			boolean needed = settings.getBoolean(tag, true);
    			if (tmpName.contains(tag.toLowerCase())) {
    				oneFound = true;
    				if (!needed) {
    					toRemove.add(station);
        				tmpName = null;
        				break;	
    				}
    			}
    		}
    		
    		if (tmpName != null) {
    			boolean needed = settings.getBoolean(Const.FILTERS_STATION_OTHERS, true);
    			if (!needed && !oneFound) {
    				toRemove.add(station);
    				tmpName = null;
    			}
    		}    		
    	}
        
        for (Station out : toRemove) {
        	stationList.results.remove(out);
        }
    	
    	return stationList;
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.option_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		switch (item.getItemId()) 
		{
		case R.id.refresh : 
			refreshStationList();
			return true;
		case R.id.filter_distance:
		    DialogFragment newFragment = new DialogFilters();
		    newFragment.show(getFragmentManager(), "filters");
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	class MyTabListener implements ActionBar.TabListener {
		public Fragment fragment_;

		public MyTabListener(Fragment fragment) {
			this.fragment_ = fragment;
		}
		
		@Override
		public void onTabReselected(Tab arg0, FragmentTransaction ft) {
			
		}

		@Override
		public void onTabSelected(Tab arg0, FragmentTransaction ft) {
			ft.replace(R.id.fragment_container, fragment_);
			onStationListUpdated();
		}

		@Override
		public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
			ft.remove(fragment_);
		}
	}

	@Override
	public void onDialogPositiveClick(DialogFragment dialog) {
		refreshStationList();
	}

	@Override
	public void onDialogNegativeClick(DialogFragment dialog) {		
	}
}
